package com.liber.sun.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by sunlingzhi on 2018/1/11.
 */
public class JwtUtils {


    static final long EXPIRATION_TIME = 86400*1000;//24 hour
    static final String SECRET = "thisisasecret";
    static final String TOKEN_PREFIX = "Bearer";

    public static String generateToken(String username, String password) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        map.put("typ","JWT");

        Long nowTime=System.currentTimeMillis();
        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(nowTime + EXPIRATION_TIME))
                .signWith(signatureAlgorithm,signingKey)
                .compact();
        return jwt;
    }

    public static Claims parseJWT(String token) {

        try{
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch(Exception ex)
        {
            return null;
        }
    }

}
